package com.kang.manager.controller;

import com.kang.common.R;
import com.kang.manager.entity.Brand;
import com.kang.manager.service.IBrandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/manager/brand")
@RefreshScope
@Slf4j
public class BrandController {

	@Autowired
	private IBrandService brandService;

	@Autowired
	private HttpServletRequest request;

	/**
	 * 获取品牌列表
	 *
	 * @param cookieHeader 请求头中的 Cookie 信息
	 * @return 品牌列表
	 */
	@GetMapping("/list")
	public R findAll(@RequestHeader(value = "Cookie", required = false) String cookieHeader) {
		try {
			if (cookieHeader != null) {
				// 处理 Cookie 编码
				cookieHeader = new String(cookieHeader.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
				log.info("Received Cookie: {}", cookieHeader);
			}
			return R.ok().put("list", brandService.list());
		} catch (Exception e) {
			log.error("Error processing cookie header", e);
			return R.error("Failed to process cookies");
		}
	}

	/**
	 * 获取配置信息
	 *
	 * @return 配置信息
	 */
	@GetMapping("/info")
	public R info() {
		return R.ok();
	}

	/**
	 * 根据 ID 获取品牌信息
	 *
	 * @param id 品牌 ID
	 * @return 品牌信息
	 */
	@GetMapping("/findById/{id}")
	public R findById(@PathVariable Long id) {
		return R.ok().put("brand", brandService.getById(id));
	}

	/**
	 * 添加品牌
	 *
	 * @param brand 品牌实体
	 * @return 操作结果
	 */
	@PostMapping("/add")
	public R add(@RequestBody Brand brand) {
		brandService.save(brand);
		return R.ok();
	}
}
